<template>
  <el-card class="box-card"  style="border-right: none; border-bottom: none !important; border-top: none !important;border-radius: 0;">
    <div class="card-header">
      <span>任务管理</span>
      <el-button type="primary" @click="dialogVisible = true">新增</el-button>
    </div>
    <el-form :inline="true" :model="formInline" class="form-inline">
      <el-form-item label="名称">
        <el-input v-model="formInline.title" placeholder="名称" clearable />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="formInline.categoryId" placeholder="分类" clearable>
          <el-option v-for="item in taskCategoryAllList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.state" placeholder="状态" clearable>
          <el-option label="全部" :value="''" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="lists" height="580px" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="标题" min-width="150" />
      <el-table-column prop="taskCategory.name" label="分类" min-width="150" />
      <el-table-column label="封面图" min-width="150">
        <template #default="scope">
          <img :src="scope.row.cover" alt="封面图" style="width: 50px; height: 50px; border-radius: 50%;" />
        </template>
      </el-table-column>
      <el-table-column label="上传附件" min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.is_attachment === 1 ? 'success' : 'danger'">
            {{ scope.row.is_attachment_text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status_text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" min-width="150" />
      <el-table-column prop="created_at" label="创建时间" width="160" />
      <el-table-column prop="updated_at" label="更新时间" width="160" />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="el-p"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增任务' : '编辑任务'"
    width="900px"
    top="50px"
    :close-on-click-modal="false"
  >
    <AddTaskForm
      v-if="dialogVisible"
      ref="addFormRef"
      :formData="currentFormData"
      :is-edit="dialogType === 'edit'"
      :taskCategoryList="taskCategoryList"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { taskService } from '@/api/task';
import { taskCategoryService } from '@/api/taskCategoryService';
import AddTaskForm from '@/components/AddTaskForm.vue';

const currentPage = ref(1);
const pageSize = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const dialogVisible = ref(false);
const total = ref(0);
const dialogType = ref('add');
const currentFormData = ref(null);
const addFormRef = ref(null);
const taskCategoryList = ref([]);
const taskCategoryAllList = ref([]);
const loading = ref(true);
const formInline = reactive({
  title: '',
  state: '',
  categoryId: ''
});
const lists = ref([]);

const getTaskCategoryList = async () => {
  try {
    const res = await taskCategoryService.getAllList({ status: 1 });
    taskCategoryList.value = res;
  } catch (error) {
    console.error('获取任务分类列表失败:', error);
  }
};

const getTaskCategoryAllList = async () => {
  try {
    const res = await taskCategoryService.getAllList();
    taskCategoryAllList.value = res;
  } catch (error) {
    console.error('获取所有任务分类列表失败:', error);
  }
};

const getList = async () => {
  loading.value = true;
  try {
    const params = {
      title: formInline.title,
      status: formInline.state,
      page: currentPage.value,
      pageSize: pageSize.value,
      task_category_id: formInline.categoryId
    };
    const response = await taskService.getList(params);
    lists.value = response.data || [];
    total.value = response.total || 0;
  } catch (error) {
    ElMessage.error('获取列表失败');
    lists.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

const resetForm = () => {
  formInline.title = '';
  formInline.state = '';
  formInline.categoryId = '';
  getList();
};

const handleEdit = (index, row) => {
  dialogVisible.value = true;
  dialogType.value = 'edit';
  currentFormData.value = { ...row }; // 创建新对象，确保引用发生变化
  console.log('Task - Updated currentFormData:', currentFormData.value); // 打印更新后的表单数据
};

const handleDelete = (row) => {
  ElMessageBox.confirm('是否删除该任务?', '提示', {
    type: 'warning'
  }).then(async () => {
      const res = await taskService.del(row.id).then((res) => {
        ElMessage.success('删除成功');
        getList();
      });
      
    })
    .catch(() => {});
};

const resetDialog = () => {
  dialogType.value = 'add';
  currentFormData.value = {
    title: '',
    cover: '',
    status: 1,
    attachment: '',
    content: '',
    task_category_id: null,
    price: 0,
    sort: 0,
    is_attachment: 0
  };
  if (addFormRef.value) {
    addFormRef.value.resetForm();
  }
};

watch(dialogVisible, (newVal) => {
  if (!newVal) {
    resetDialog();
  }
});

const submitForm = async () => {
  if (!addFormRef.value) return;

  const isValid = await addFormRef.value.validateForm();
  if (!isValid) return;

  try {
    const formData = { ...addFormRef.value.form };
    if (dialogType.value === 'add') {
      await taskService.add(formData);
      ElMessage.success('新增任务成功');
      resetDialog();
    } else {
      await taskService.update(formData.id, formData);
      ElMessage.success('更新任务成功');

    }
    dialogVisible.value = false;
    getList();
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '新增任务失败' : '更新任务失败');
    console.error('Form submission failed:', error);
  }
};

const onSubmit = () => {
  console.log('Submitting form with filters:', formInline); // 打印当前过滤条件
  getList(); // 调用获取列表的方法
};

// watch(() => currentFormData.value, (newVal, oldVal) => {
//   console.log('Task - currentFormData updated:', newVal, 'oldVal:', oldVal); // 打印新旧值
// });

getTaskCategoryList();
getTaskCategoryAllList();
getList();
</script>

<style scoped>
.form-inline {
  margin: 20px 0;
  border-bottom: 1px solid #e4e7ed;
}
.el-p {
  margin-top: 15px;
  display: flex;
  justify-self: flex-end;
}
.el-select {
  width: 100px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  border-bottom: 1px solid #e4e7ed;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.el-descriptions {
  margin: 20px;
}
</style>
